package cn.webrx;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@SpringBootApplication
@Slf4j
public class App implements ApplicationRunner {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //log.info("hello world "+ SpringBootVersion.getVersion());

        //-------------------------生成令牌
        //令牌有效期 10分钟
        Date date = new Date(System.currentTimeMillis()+1000*60*10);
        //签名
        String secret = "webrx";
        JWTCreator.Builder builder = JWT.create();
        Map<String, Object> header = new HashMap<>();
        header.put("alg","HS256");
        header.put("typ","JWT");
        String t1 = builder.withHeader(header).withClaim("name","张三丰").withExpiresAt(date).sign(Algorithm.HMAC256(secret));
        System.out.println(t1);
        //

        //-------------------------校验令牌
        //String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoi5byg5LiJ5LiwIiwiZXhwIjoxNjk1NzEwNzc2fQ.12x9-83lQ6Du_NmEAmbaFTMADGT-HBafvii4IcfslKM";
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoi5byg5LiJ5LiwIiwiZXhwIjoxNjk1NzEwNzc2fQ.12x9-83lQ6Du_NmEAmbaFTMADGT-HBafvii4IcfslKM";
        //检查
        JWTVerifier jwtver = JWT.require(Algorithm.HMAC256(secret)).build();
        try {
            DecodedJWT dec = jwtver.verify(token);
            System.out.printf("%tF %<tT", dec.getExpiresAt());

        } catch (TokenExpiredException e) {
            System.out.println("令牌过期");
        } catch (JWTDecodeException jwtDecodeException) {
            System.out.println("令牌格式不正确");
        } catch (Exception ex) {
            System.out.println("令牌无效");
        }

        // 指定token过期时间为10秒
        //Calendar calendar = Calendar.getInstance();
        //calendar.add(Calendar.SECOND, 10);

        //String token = JWT.create().sign(Algorithm.HMAC256("webrx"));
        //String token = JWT.create()
        //.withHeader(new HashMap<>())  // Header 格式规范
        //.withClaim("userId", 21)  // Payload 数据
        //.withClaim("userName", "admin")
        //        .withExpiresAt(calendar.getTime())  // 参数要求是java.util.Date 实例 ，过期时间
        //        .sign(Algorithm.HMAC256("webrx"));  // 签名用的webrx


        //System.out.println(token);
    }
}
